package com.qi.demo01.Lock8;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author zjq
 * @date 2020/3/31 20:10
 */
//自旋锁
public class SpinlockDemo {

    AtomicReference<Thread> atomicReference = new AtomicReference();

    //加锁
    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "myLock");
        //自旋锁 使用CAS实现自旋锁
        while (!atomicReference.compareAndSet(null, thread)) {

        }
    }


    //解锁
    public void myUnLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "myUnLock");
        atomicReference.compareAndSet(thread, null);
    }

}
